package com.btl.component.crypto.aes.advice;

import com.btl.boot.core.dto.response.R;
import com.btl.component.crypto.aes.AesSecurityCrypt;
import com.btl.component.crypto.aes.SecurityCrypt;
import com.btl.component.crypto.aes.annotation.AesSec;
import com.btl.component.crypto.aes.exception.EncryptException;
import com.btl.component.crypto.aes.util.AESCryptoUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

@Slf4j
@ControllerAdvice
public class AesEncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean supports(MethodParameter returnType, @NonNull Class converterType) {
        return returnType.hasMethodAnnotation(AesSec.class)
                && R.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public Object beforeBodyWrite(Object body, @NonNull MethodParameter returnType, @NonNull MediaType mediaType, @NonNull Class converterType, @NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response) {
        if (body instanceof R<?> r && r.getData() != null && r.getCode() == 0) {
            String keyId = request.getHeaders()
                    .getFirst("Sec-Key-Id");
            if (StringUtils.hasText(keyId)) {
                Object key = redisTemplate.opsForValue()
                        .get(keyId);
                if (Objects.nonNull(key)) {
                    return R.ok(AesSecurityCrypt.encrypt(key.toString(), r.getData()));
                }
            } else {
                throw new EncryptException("加密异常");
            }
        }
        return body;
    }
}
